#include "font_config.h"
#include "utils/gui_dfx.h"
#include <fstream>
#include <iostream>
#include <istream>

using namespace nlohmann;

namespace YueGUI {
FontConfig::FontConfig() {}

FontConfig::~FontConfig() {}

void FontConfig::SetOutputFormat(OutputFormat format) { format_ = format; }

OutputFormat FontConfig::GetOutputFormat() const { return format_; }

int32_t FontConfig::LoadFontConfigFile(const std::string &path) {
    std::ifstream inFile(path);
    json config;
    std::string test;
    inFile >> config;
    Dfx::Log(LogLevel::DEBUG, config.dump().c_str());
    if (config.size() <= 0) {
        return GUIError::FONT_CONFIG_FILE_IS_ILLEGL;
    } else {
        return ConvertToGlyphRangeMap(config);
    }
}

int32_t FontConfig::ConvertToGlyphRangeMap(const json &jsonConfig) {
    if (jsonConfig[JSON_LIST] == nullptr) {
        return GUIError::FONT_CONFIG_FILE_IS_EMPTY;
    }

    uint32_t fontTotalNum = jsonConfig[JSON_LIST].size();
    for (uint32_t perFontIndex = 0; perFontIndex < fontTotalNum;
         perFontIndex++) {
        json perFontConfig = jsonConfig[JSON_LIST][perFontIndex];
        ConvertFontConfig(perFontConfig);
    }
    return GUIError::SUCCESS;
}

int32_t FontConfig::ConvertFontConfig(const json &fontConfig) {
    std::vector<UnicodeRange> value;
    json glyphRange = fontConfig[JSON_GLYPH_RANGE];
    for (uint32_t i = 0; i < glyphRange.size(); i++) {
        UnicodeRange range;
        range.min = glyphRange[i][JSON_RANGE_MIN];
        range.max = glyphRange[i][JSON_RANGE_MAX];
        value.push_back(range);
    }

    FontKey key;
    key.fontName = fontConfig[JSON_FONT_NAME];
    key.fontSize = fontConfig[JSON_FONT_SIZE];

    glyphRangeMap_[key] = value;
    return GUIError::SUCCESS;
}
bool FontKey::operator<(const FontKey &right) const {
    if (fontName != right.fontName) {
        return fontName < right.fontName;
    } else {
        return fontSize < right.fontSize;
    }
}
} // namespace YueGUI